package com.mcxx.modules.tool.service;

import com.mcxx.common.exception.BizException;
import com.mcxx.modules.tool.service.impl.YinhaiSubsistenceService;
import com.mcxx.modules.tool.service.impl.YinhaiTempAssTService;
import com.mcxx.modules.base.service.read.AreaReadService;
import com.mcxx.modules.system.dto.AreaMappingDTO;
import com.mcxx.result.BaseResult;
import com.mcxx.util.CommonUtil;
import com.mcxx.util.Constant;
import com.mcxx.util.DateUtil;
import com.mcxx.util.FailureCode;
import com.yinhai.ta404.core.transaction.annotation.TaTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;


@Slf4j
@Service
@TaTransactional
public class GenerateYinhaiService {

    @Autowired
    private AreaReadService areaReadService;
    @Autowired
    private YinhaiSubsistenceService yinhaiSubsistenceService;
    @Autowired
    private YinhaiTempAssTService yinhaiTempAssTService;

    public BaseResult<Boolean> yinhaiData(String strAreaCodes, String strMonths, String busiCode) {
        BaseResult<Boolean> result = new BaseResult<Boolean>();
        if(CommonUtil.invalidArgs(strMonths) || CommonUtil.invalidArgs(strAreaCodes)) {
            throw new BizException(FailureCode.ERR_10000);
        }
        Date date = DateUtil.str2Date(strMonths+"01", DateUtil.sdf6);
        strMonths = DateUtil.sdf2.format(date);
        String[] areaCodes = strAreaCodes.split(",");
        for(String areaCode : areaCodes){

            List<AreaMappingDTO> areaCodeBycCodeALevle = areaReadService.getAreaCodeBycCodeALevle(areaCode);
            if(CollectionUtils.isNotEmpty(areaCodeBycCodeALevle)){
                for(AreaMappingDTO dto : areaCodeBycCodeALevle){
                    String queryAreaCode = dto.getAreaCode().substring(0, 6);

                    if(StringUtils.isEmpty(busiCode)){

                        yinhaiSubsistenceService.dibaotekunData(queryAreaCode,strMonths,"110");
                        yinhaiSubsistenceService.dibaotekunData(queryAreaCode,strMonths,"130");
                        yinhaiTempAssTService.linshiData(dto.getAreaCode(),strMonths);
                    }else{

                        if(!Constant.BusinessCode.LINSHI.equals(busiCode)){
                            yinhaiSubsistenceService.dibaotekunData(queryAreaCode,strMonths,busiCode);
                        }else{
                            yinhaiTempAssTService.linshiData(queryAreaCode,strMonths);
                        }
                    }



                }
            }else{
                throw new BizException("-1","区划未查询到数据");
            }
        }
        return null;
    }
}
